import { NestFactory } from '@nestjs/core'
import { ValidationPipe, Logger } from '@nestjs/common'
import { AppModule } from './app.module'
import * as session from 'express-session'
import * as express from 'express'
import * as cors from 'cors'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
import { LoggerMiddleware } from './middleware/logger.middleware'
import { NestExpressApplication } from '@nestjs/platform-express'
import { join } from 'path'
import * as dotenv from 'dotenv'
dotenv.config({
  path: `${process.env.NODE_ENV === 'development' ? '.env.dev' : '.env.prod'}`
})

const PORT = process.env.PORT || 3000
const PREFIX = process.env.PREFIX || '/'
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule)
  app.use(cors()) // 允许跨域请求
  app.use(express.json()) // For parsing application/json
  app.use(express.urlencoded({ extended: true })) // For parsing application/x-www-form-urlencoded
  // 监听所有的请求路由，并打印日志
  app.use(new LoggerMiddleware().use)
  // 配置文件静态资源
  app.useStaticAssets(join(__dirname, '../images'), {
    prefix: '/img'
  })
  app.use(
    session({
      secret: 'XiaoFeng',
      name: 'xf.session',
      rolling: true,
      cookie: { maxAge: null }
    })
  )

  app.useGlobalPipes(new ValidationPipe())
  //配置swagger
  const swaggerOptions = new DocumentBuilder()
    .setTitle('nestjs-api-文档') //文档标题
    .setDescription('nestjs-api-说明') //文档描述
    .setVersion('1.0') //文档版本
    .addBasicAuth() //鉴权，可以输入token
    .build() //创建
  //创建swagger
  const document = SwaggerModule.createDocument(app, swaggerOptions)
  //启动swagger
  SwaggerModule.setup('doc', app, document) // 访问路径为 localhost:8000/doc
  await app.listen(PORT, () => {
    Logger.log(`服务已经启动,接口请访问:http://wwww.localhost:${PORT}`)
    Logger.log(
      `服务已经启动,swagger文档请访问:http://wwww.localhost:${PORT}/doc`
    )
    Logger.log(
      `服务已经启动,接口请访问:http://wwww.localhost:${PORT}/${PREFIX}`
    )
  })
}
bootstrap()
